<template>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
        <el-form-item label="订单编号" prop="orderCode">
          <el-input
            v-model="queryParams.orderCode"
            placeholder="请输入订单编号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="供应商" prop="supplierId">
          <el-select v-model="queryParams.supplierId" placeholder="请选择供应商" clearable>
            <el-option
              v-for="item in supplierOptions"
              :key="item.supplierId"
              :label="item.supplierName"
              :value="item.supplierId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="采购员" prop="staffId">
          <el-select v-model="queryParams.staffId" placeholder="请选择采购员" clearable>
            <el-option
              v-for="item in staffOptions"
              :key="item.staffId"
              :label="item.staffName"
              :value="item.staffId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="订单状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择订单状态" clearable>
            <el-option label="待审核" value="0" />
            <el-option label="已审核" value="1" />
            <el-option label="采购中" value="2" />
            <el-option label="已入库" value="3" />
            <el-option label="已取消" value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="下单日期" prop="orderDate">
          <el-date-picker clearable
            v-model="queryParams.orderDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择下单日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
  
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['system:SysPurchaseOrder:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:SysPurchaseOrder:edit']"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:SysPurchaseOrder:remove']"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['system:SysPurchaseOrder:export']"
          >导出</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
  
      <el-table v-loading="loading" :data="SysPurchaseOrderList" @selection-change="handleSelectionChange" border stripe>
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="采购订单ID" align="center" prop="orderId" width="80" />
        <el-table-column label="订单编号" align="center" prop="orderCode" width="120" />
        <el-table-column label="供应商" align="center" width="120">
          <template slot-scope="scope">
            {{ getSupplierName(scope.row.supplierId) }}
          </template>
        </el-table-column>
        <el-table-column label="采购员" align="center" width="100">
          <template slot-scope="scope">
            {{ getStaffName(scope.row.staffId) }}
          </template>
        </el-table-column>
        <el-table-column label="商品" align="center" min-width="150">
          <template slot-scope="scope">
            <div v-if="scope.row.productId">
              <el-tag v-for="(product, index) in parseProductIds(scope.row.productId)" 
                     :key="index" 
                     size="mini" 
                     style="margin: 2px">
                {{ getProductName(product) }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="订单总金额" align="center" width="120">
          <template slot-scope="scope">
            <span class="price-tag">¥ {{ formatPrice(scope.row.totalAmount) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="下单日期" align="center" width="100">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.orderDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="预计到货日期" align="center" width="100">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.expectedDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="实际到货日期" align="center" width="100">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.actualDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="入库仓库" align="center" width="120">
          <template slot-scope="scope">
            {{ getWarehouseName(scope.row.warehouseId) }}
          </template>
        </el-table-column>
        <el-table-column label="订单状态" align="center" width="100">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusName(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" min-width="120" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:SysPurchaseOrder:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:SysPurchaseOrder:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
  
      <!-- 添加或修改采购订单对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="订单编号" prop="orderCode">
                <el-input v-model="form.orderCode" placeholder="自动生成" :disabled="true" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="供应商" prop="supplierId">
                <el-select v-model="form.supplierId" placeholder="请选择供应商" style="width: 100%">
                  <el-option
                    v-for="item in supplierOptions"
                    :key="item.supplierId"
                    :label="item.supplierName"
                    :value="item.supplierId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row>
            <el-col :span="12">
              <el-form-item label="采购员" prop="staffId">
                <el-select v-model="form.staffId" placeholder="请选择采购员" style="width: 100%">
                  <el-option
                    v-for="item in staffOptions"
                    :key="item.staffId"
                    :label="item.staffName"
                    :value="item.staffId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="入库仓库" prop="warehouseId">
                <el-select v-model="form.warehouseId" placeholder="请选择入库仓库" style="width: 100%">
                  <el-option
                    v-for="item in warehouseOptions"
                    :key="item.warehouseId"
                    :label="item.warehouseName"
                    :value="item.warehouseId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-form-item label="商品选择" prop="productIds">
            <el-select
              v-model="selectedProducts"
              multiple
              filterable
              placeholder="请选择商品"
              style="width: 100%"
              @change="handleProductChange"
            >
              <el-option
                v-for="item in productOptions"
                :key="item.productId"
                :label="item.productName"
                :value="item.productId"
              >
                <span>{{ item.productName }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">¥{{ formatPrice(item.price) }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          
          <el-table v-if="selectedProducts.length > 0" :data="productDetails" border style="width: 100%; margin-bottom: 20px">
            <el-table-column prop="productName" label="商品名称" width="180"></el-table-column>
            <el-table-column prop="unitPrice" label="单价" width="120">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.unitPrice" :precision="2" :step="0.01" :min="0" size="mini" style="width: 100%"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column prop="quantity" label="数量" width="150">
              <template slot-scope="scope">
                <el-input-number 
                  v-model="scope.row.quantity" 
                  :min="1" 
                  :precision="0" 
                  size="mini" 
                  @change="calculateItemTotal(scope.row)"
                  style="width: 100%"
                  controls-position="right"
                ></el-input-number>
              </template>
            </el-table-column>
            <el-table-column prop="totalPrice" label="小计">
              <template slot-scope="scope">
                ¥ {{ formatPrice(scope.row.totalPrice) }}
              </template>
            </el-table-column>
          </el-table>
          
          <el-row>
            <el-col :span="8">
              <el-form-item label="订单总金额" prop="totalAmount">
                <el-input v-model="form.totalAmount" placeholder="订单总金额" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="商品总数量" prop="quantity">
                <el-input v-model="form.quantity" placeholder="商品总数量" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="下单日期" prop="orderDate">
                <el-date-picker
                  v-model="form.orderDate"
                  type="date"
                  placeholder="请选择下单日期"
                  value-format="yyyy-MM-dd"
                  style="width: 100%"
                ></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row>
            <el-col :span="12">
              <el-form-item label="预计到货日期" prop="expectedDate">
                <el-date-picker
                  v-model="form.expectedDate"
                  type="date"
                  placeholder="请选择预计到货日期"
                  value-format="yyyy-MM-dd"
                  style="width: 100%"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="实际到货日期" prop="actualDate">
                <el-date-picker
                  v-model="form.actualDate"
                  type="date"
                  placeholder="请选择实际到货日期"
                  value-format="yyyy-MM-dd"
                  style="width: 100%"
                ></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row>
            <el-col :span="12">
              <el-form-item label="订单状态" prop="status">
                <el-select v-model="form.status" placeholder="请选择订单状态" style="width: 100%">
                  <el-option label="待审核" value="0" />
                  <el-option label="已审核" value="1" />
                  <el-option label="采购中" value="2" />
                  <el-option label="已入库" value="3" />
                  <el-option label="已取消" value="4" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import { listSysPurchaseOrder, getSysPurchaseOrder, delSysPurchaseOrder, addSysPurchaseOrder, updateSysPurchaseOrder } from "@/api/system/SysPurchaseOrder";
  import { listSysProcurementStaff, getSysProcurementStaff } from "@/api/system/SysProcurementStaff";
  import { listSysProduct, getSysProduct } from "@/api/system/SysProduct";
  import { listSysSupplier, getSysSupplier } from "@/api/system/SysSupplier";
  import { listSysWarehouse, getSysWarehouse } from "@/api/system/SysWarehouse";
  
  export default {
    name: "SysPurchaseOrder",
    data() {
      // Custom validator for product selection
      const validateProducts = (rule, value, callback) => {
        if (this.selectedProducts && this.selectedProducts.length > 0) {
          callback();
        } else {
          callback(new Error('请选择至少一个商品'));
        }
      };

      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 采购订单表格数据
        SysPurchaseOrderList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 供应商选项
        supplierOptions: [],
        // 采购员选项
        staffOptions: [],
        // 仓库选项
        warehouseOptions: [],
        // 商品选项
        productOptions: [],
        // 已选择的商品ID列表
        selectedProducts: [],
        // 商品详情列表（包含数量、单价等）
        productDetails: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          orderCode: null,
          supplierId: null,
          staffId: null,
          productId: null,
          quantity: null,
          unitPrice: null,
          totalPrice: null,
          totalAmount: null,
          orderDate: null,
          expectedDate: null,
          actualDate: null,
          warehouseId: null,
          status: null,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          orderCode: [
            { required: true, message: "订单编号不能为空", trigger: "blur" }
          ],
          supplierId: [
            { required: true, message: "供应商不能为空", trigger: "change" }
          ],
          staffId: [
            { required: true, message: "采购员不能为空", trigger: "change" }
          ],
          orderDate: [
            { required: true, message: "下单日期不能为空", trigger: "blur" }
          ],
          status: [
            { required: true, message: "订单状态不能为空", trigger: "change" }
          ],
          warehouseId: [
            { required: true, message: "入库仓库不能为空", trigger: "change" }
          ],
          productIds: [
            { validator: validateProducts, trigger: "change" }
          ]
        }
      };
    },
    created() {
      this.getList();
      this.getSupplierOptions();
      this.getStaffOptions();
      this.getWarehouseOptions();
      this.getProductOptions();
    },
    methods: {
      /** 查询采购订单列表 */
      getList() {
        this.loading = true;
        listSysPurchaseOrder(this.queryParams).then(response => {
          this.SysPurchaseOrderList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      /** 获取供应商选项 */
      getSupplierOptions() {
        listSysSupplier().then(response => {
          this.supplierOptions = response.rows;
        });
      },
      /** 获取采购员选项 */
      getStaffOptions() {
        listSysProcurementStaff().then(response => {
          this.staffOptions = response.rows;
        });
      },
      /** 获取仓库选项 */
      getWarehouseOptions() {
        listSysWarehouse().then(response => {
          this.warehouseOptions = response.rows;
        });
      },
      /** 获取商品选项 */
      getProductOptions() {
        listSysProduct().then(response => {
          this.productOptions = response.rows;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          orderId: null,
          orderCode: null,
          supplierId: null,
          staffId: null,
          productId: null,
          quantity: null,
          unitPrice: null,
          totalPrice: "0.00",
          totalAmount: 0,
          orderDate: this.parseTime(new Date(), '{y}-{m}-{d}'),
          expectedDate: null,
          actualDate: null,
          warehouseId: null,
          status: "0", // 默认为待审核
          remark: null,
          delFlag: "0",
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null
        };
        this.selectedProducts = [];
        this.productDetails = [];
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.orderId)
        this.single = selection.length!==1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.form.orderCode = this.generateOrderCode();
        this.open = true;
        this.title = "添加采购订单";
      },
      /** 生成订单编号 */
      generateOrderCode() {
        const now = new Date();
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0');
        const day = String(now.getDate()).padStart(2, '0');
        const hour = String(now.getHours()).padStart(2, '0');
        const minute = String(now.getMinutes()).padStart(2, '0');
        const second = String(now.getSeconds()).padStart(2, '0');
        const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
        
        return `PO${year}${month}${day}${hour}${minute}${second}${random}`;
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const orderId = row.orderId || this.ids
        getSysPurchaseOrder(orderId).then(response => {
          this.form = response.data;
          
          // 解析商品ID JSON
          if (this.form.productId) {
            try {
              const productInfo = JSON.parse(this.form.productId);
              if (Array.isArray(productInfo)) {
                if (productInfo.length > 0 && productInfo[0].hasOwnProperty('productId')) {
                  // 新格式：提取productId数组
                  this.selectedProducts = productInfo.map(item => item.productId);
                } else {
                  // 旧格式：直接使用
                  this.selectedProducts = productInfo;
                }
                this.loadProductDetails();
              }
            } catch (e) {
              console.error("解析商品ID JSON失败", e);
              this.selectedProducts = [];
            }
          }
          
          this.open = true;
          this.title = "修改采购订单";
        });
      },
      /** 处理商品选择变化 */
      handleProductChange() {
        this.loadProductDetails();
        // Trigger validation for productIds field when selection changes
        this.$nextTick(() => {
          this.$refs.form.validateField('productIds');
        });
      },
      /** 加载商品详情 */
      loadProductDetails() {
        this.productDetails = [];
        
        // 从已有表单中获取商品详情
        const existingDetails = {};
        if (this.form.orderId && this.form.productDetails) {
          try {
            const details = JSON.parse(this.form.productDetails);
            details.forEach(item => {
              existingDetails[item.productId] = item;
            });
          } catch (e) {
            console.error("解析商品详情失败", e);
          }
        }
        
        // 为每个选中的商品创建详情
        this.selectedProducts.forEach(productId => {
          const product = this.productOptions.find(p => p.productId === productId);
          if (product) {
            // 使用已有详情或创建新详情
            const existing = existingDetails[productId];
            const detail = {
              productId: product.productId,
              productName: product.productName,
              unitPrice: existing ? existing.unitPrice : product.costPrice || 0,
              quantity: existing ? existing.quantity : 1,
              totalPrice: 0
            };
            
            // 计算小计
            detail.totalPrice = detail.unitPrice * detail.quantity;
            
            this.productDetails.push(detail);
          }
        });
        
        this.calculateOrderTotal();
        this.calculateTotalQuantity();
      },
      /** 计算商品小计 */
      calculateItemTotal(item) {
        item.totalPrice = item.unitPrice * item.quantity;
        this.calculateOrderTotal();
        this.calculateTotalQuantity();
      },
      /** 计算订单总金额 */
      calculateOrderTotal() {
        let total = 0;
        this.productDetails.forEach(item => {
          total += item.totalPrice;
        });
        this.form.totalAmount = total.toFixed(2);
        this.form.totalPrice = total.toFixed(2);
      },
      /** 计算商品总数量 */
      calculateTotalQuantity() {
        let totalQuantity = 0;
        this.productDetails.forEach(item => {
          totalQuantity += parseInt(item.quantity || 0);
        });
        this.form.quantity = totalQuantity;
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            // Create product info array with name and quantity
            const productInfo = this.productDetails.map(item => {
              return {
                productId: item.productId,
                productName: item.productName,
                quantity: item.quantity
              };
            });
            
            // Store product info as JSON in productId field
            this.form.productId = JSON.stringify(productInfo);
            
            // Save product details
            this.form.productDetails = JSON.stringify(this.productDetails);
            
            // Make sure total_price is set - this is the missing field causing the error
            if (!this.form.totalPrice) {
              // If totalPrice is not set, use the same value as totalAmount
              this.form.totalPrice = this.form.totalAmount;
            }
            
            if (this.form.orderId != null) {
              updateSysPurchaseOrder(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addSysPurchaseOrder(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const orderIds = row.orderId || this.ids;
        this.$modal.confirm('是否确认删除采购订单编号为"' + orderIds + '"的数据项？').then(function() {
          return delSysPurchaseOrder(orderIds);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('system/SysPurchaseOrder/export', {
          ...this.queryParams
        }, `SysPurchaseOrder_${new Date().getTime()}.xlsx`)
      },
      // 获取供应商名称
      getSupplierName(supplierId) {
        const supplier = this.supplierOptions.find(item => item.supplierId === supplierId);
        return supplier ? supplier.supplierName : supplierId;
      },
      // 获取采购员名称
      getStaffName(staffId) {
        const staff = this.staffOptions.find(item => item.staffId === staffId);
        return staff ? staff.staffName : staffId;
      },
      // 获取仓库名称
      getWarehouseName(warehouseId) {
        const warehouse = this.warehouseOptions.find(item => item.warehouseId === warehouseId);
        return warehouse ? warehouse.warehouseName : warehouseId;
      },
      // 获取商品名称
      getProductName(productId) {
        const product = this.productOptions.find(item => item.productId === productId);
        return product ? product.productName : productId;
      },
      // 解析商品ID JSON
      parseProductIds(productIdJson) {
        if (!productIdJson) return [];
        try {
          const productInfo = JSON.parse(productIdJson);
          if (Array.isArray(productInfo)) {
            // 如果是数组，检查是否包含productId属性
            if (productInfo.length > 0 && productInfo[0].hasOwnProperty('productId')) {
              // 新格式：返回productId数组
              return productInfo.map(item => item.productId);
            } else {
              // 旧格式：直接返回
              return productInfo;
            }
          }
          return [];
        } catch (e) {
          console.error("解析商品ID JSON失败", e);
          return [];
        }
      },
      // 格式化价格
      formatPrice(price) {
        if (price === null || price === undefined || price === '') {
          return '0.00';
        }
        return parseFloat(price).toFixed(2);
      },
      // 获取订单状态名称
      getStatusName(status) {
        const statusMap = {
          '0': '待审核',
          '1': '已审核',
          '2': '采购中',
          '3': '已入库',
          '4': '已取消'
        };
        return statusMap[status] || status;
      },
      // 获取订单状态标签类型
      getStatusType(status) {
        const typeMap = {
          '0': 'info',
          '1': 'success',
          '2': 'primary',
          '3': 'success',
          '4': 'danger'
        };
        return typeMap[status] || '';
      }
    }
  };
  </script>
  
  <style scoped>
  .price-tag {
    color: #409EFF;
    font-weight: bold;
  }
  .mb8 {
    margin-bottom: 8px;
  }
  .el-table {
    margin-top: 15px;
  }
  </style>